import 'quill/dist/quill.snow.css'
import './editor.css'

import Quill from 'quill'
import file from './fileload.js'
import VideoBlot from './video.js'
import config from '../../common/config.js'
import store from '../../store/index'
import g from '../../common/g.js'

export default {
  props: {
    toolbaroptions: {
      type: [Array, String, String],
      default: function () {
        // return [
        //   ['bold'],
        //   ['italic'],
        //   ['underline'],
        //   ['blockquote'],
        //   ['image'],
        //   [{ 'header': 1 }],
        //   [{ 'header': 2 }],
        //   [{'list': 'ordered'}, { 'list': 'bullet' }],
        //   [{'align': []}],
        //   ['link']
        // ]
        return [
          ['bold', 'italic', 'underline'],
          ['blockquote'],
          [{ 'header': [1, 2, 3, 4, 5, 6] }],
          [{ 'list': 'ordered'}, { 'list': 'bullet' }],
          [{ 'indent': '-1'}, { 'indent': '+1' }],
          [{ 'align': [] }],
          [{ 'color': [] }, { 'background': [] }],
          ['link', 'image', 'video', 'file'],
          ['clean']
        ]
      }
    },
    placeholder: {
      type: String,
      default: '请输入内容...'
    },
    winheight: {
      type: String,
      default: '380px'
    }
  },
  data: function () {
    return {
      editor: {},
      config: config,
      uploadShow: false,
      uploadList: [],
      uploadNum: 0,
      refreshAuth: false,
      accept: 'image/*',
      uploadType: 'image',
      header: {Authorization: 'Bearer ' + store.getters.auth('jwt')}
    }
  },
  mounted: function () {
    this.create()
  },
  methods: {
    create: function () {
      let that = this
      let options = {
        modules: {
          toolbar: {
            container: this.toolbaroptions,
            handlers: {
              'image': function (value) {
                that.accept = 'image/*'
                that.uploadType = 'image'
                if (value) {
                  that.$refs.plEditorUploader.$children[0].$refs.input.accept = that.accept
                  that.$refs.plEditorUploader.$children[0].$refs.input.click()
                } else {
                  that.editor.format('image', false)
                }
              },
              'file': function (value) {
                that.accept = 'application/*'
                that.uploadType = 'file'
                if (value) {
                  that.$refs.plEditorUploader.$children[0].$refs.input.accept = that.accept
                  that.$refs.plEditorUploader.$children[0].$refs.input.click()
                } else {
                  that.editor.format('file', false)
                }
              },
              'video': function (value) {
                that.accept = 'video/*'
                that.uploadType = 'video'
                if (value) {
                  that.$refs.plEditorUploader.$children[0].$refs.input.accept = that.accept
                  that.$refs.plEditorUploader.$children[0].$refs.input.click()
                } else {
                  that.editor.format('video', false)
                }
              },
            }
          }
        },
        placeholder: this.placeholder,
        theme: 'snow'
      }
      Quill.register(VideoBlot)
      this.editor = new Quill(this.$refs.plEditor, options)
      this.editor.on('text-change', function (delta, oldDelta, source) {
        that.$emit('text-change', delta)
      })
      this.editor.root.addEventListener('paste', e => {
        const files = [...e.clipboardData.files]
        if (files.length > 0) {
          this.$message.info('粘贴内容包含文件，请使用菜单栏工具进行上传!')
        }
      }, false)
    },
    uploadSuccess: function (response, file, fileList) {
      this.uploadList.push(file.uid)
      if (response.status === 400) {
        file.status = 'error'
        file.name += ' (上传失败)'
        let authErrors = ['auth_empty', 'auth_error', 'auth_refresh_error', 'auth_timeout']
        if (authErrors.indexOf(response.msg) >= 0 && this.refreshAuth === false) {
          if (response.msg !== 'auth_timeout') {
            store.dispatch('loginNeed')
          } else {
            this.refreshAuth = true
            g.refreshJwt(() => {
              this.refreshAuth = false
            })
          }
        }
      }
      if (this.uploadList.length === fileList.length) {
        this.uploadEnd(fileList)
      }
    },
    uploadRemove: function (file, fileList) {
      this.uploadList = this.uploadList.filter((item) => item !== file.uid)
    },
    uploadError (err, file, fileList) {
      this.uploadList.push(file.uid)
      if (this.uploadList.length === fileList.length) {
        this.uploadEnd(fileList)
      }
    },
    beforeUp: function (file) {
      let re = true
      if (this.uploadType === 'image') {

        re = this.beforeUpload(file)
      } else if(this.uploadType === 'file') {

        re = this.beforeUploadFile(file)
      } else {

        re = this.beforeUploadVideo(file)
      }
      if (!re) {
        this.uploadShow = false
        return false
      }
    },
    beforeUploadVideo: function (file) {
      this.uploadShow = true
      const isLt10M = file.size / 1024 / 1024 < 100

      const isOGM = file.type === 'video/ogm'
      const isOGV = file.type === 'video/ogg'
      const isWMV = file.type === 'video/wmv'
      const isMPEG = file.type === 'video/mpeg'
      const isMOV = file.type === 'video/quicktime'
      const isMP4 = file.type === 'video/mp4'
      const isAVI = file.type === 'video/x-msvideo'

      if (!isLt10M) {
        this.$message.error(file.name + ' 大小超过了 100MB,只允许上传不超过100MB的视频')
        return false
      }
      if (!isOGM && !isOGV && !isWMV && !isMPEG && !isMOV && !isMP4 && !isAVI) {
        this.$message.error( file.name + ' 格式不是 OGM/OGV/WMV/MPEG/MOV/MP4/AVI 其中一种')
        return false
      }

      return true
    },
    beforeUploadFile: function (file) {
      this.uploadShow = true
      const isLt10M = file.size / 1024 / 1024 < 20

      const isPDF = file.type === 'application/pdf'
      const isZIP = file.type === 'application/x-zip-compressed'
      const isRAR = file.type === 'application/x-rar-compressed'
      const isDOC = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      const isDOCX = file.type === 'application/msword'

      if (!isLt10M) {
        this.$message.error(file.name + ' 大小超过了 20MB,只允许上传不超过20MB的文件')
        return false
      }

      if (!isPDF && !isZIP && !isDOC && !isDOCX && !isRAR) {
        this.$message.error(file.name + ' 格式不是 PDF/DOC/DOCX/ZIP 其中一种')
        return false
      }

      return true
    },
    beforeUpload: function (file) {
      this.uploadShow = true
      const isLt2M = file.size / 1024 / 1024 < 10
      const isJPEG = file.type === 'image/jpeg'
      const isJPG = file.type === 'image/jpg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'

      if (!isLt2M) {
        this.$message.error(file.name + ' 大小超过了 10MB,只允许上传不超过10MB的图片')
        return false
      }

      if (!isJPG && !isJPEG && !isPNG && !isGIF) {
        this.$message.error(file.name + ' 格式不是 JPG/JPEG/PNG/GIF 其中一种')
        return false
      }

      return true
    },
    uploadExceed: function (files) {
      this.$message.warning(`只能选择 10 个文件，本次选择了 ${files.length} 个文件`)
    },
    uploadEnd: function (fileList) {
      this.uploadList = []
      setTimeout(() => {
        this.$refs.plEditorUploader.clearFiles()
        this.uploadShow = false
      }, 1000)
      for (let v in fileList) {
        let res = fileList[v]
        for (let v in fileList) {
          let res = fileList[v]
          if (res.status === 'success') {
            let length = this.editor.getSelection().index
            if (this.uploadType === 'image') {
              this.editor.insertEmbed(length, 'image', config.imgURI + res.response.memo.fullName)
            } else if(this.uploadType === 'file') {
              this.editor.insertText(length, res.response.memo.oriName, 'link', config.imgURI + res.response.memo.fullName)
            } else {
              let url = config.imgURI + res.response.memo.fullName
              this.editor.insertEmbed(length, 'sVideo', {
                url,
                controls: 'controls',
                width: '100%',
                height: '100%'
              })
            }
            this.editor.setSelection(length + 2)
          }
        }
      }
    },
    getContent: function () {
      return this.editor.getContents()
    },
    setContent: function (content) {
      this.editor.setContents(content)
    },
    setFocus: function () {
      this.editor.focus()
    }
  },
  template: '<div class="kk-editor" :style="\'height: \' + winheight"  ref="kkEditor">' +
  '<div ref="plEditor" ></div><div class="kk-editor-mask" v-show="uploadShow"><div class="kk-editor-uploader" >' +
  '<el-upload ref="plEditorUploader" :action="config.upURI" :headers="header" :multiple="true"  :on-exceed="uploadExceed" list-type="picture"' +
  ':show-file-list="true" :on-remove="uploadRemove" :on-success="uploadSuccess" :on-error="uploadError" :before-upload="beforeUp" :limit="10" ></el-upload>' +
  '</div></div></div>'
}
